#include "header.h"

void *checkThreadFunction(void *ptr)
{
	//lock
	checkActive = true;
	//unlock
	checkFlag = false;;



	Header checkHeader = createHeader((uint8_t) checkRequestMessageType,0);					//0xF6

	Messages msg;
	msg.Header = (char *)malloc(27 *sizeof(char));
	memcpy(&msg.Header[0],&checkHeader.messageType,1);
	memcpy(&msg.Header[1],checkHeader.uoid,20);
	memcpy(&msg.Header[21],&checkHeader.ttl,1);
	memcpy(&msg.Header[22],&checkHeader.reserved,1);
	memcpy(&msg.Header[23],&checkHeader.dataLength,4);

	string tempUOID((const char*)checkHeader.uoid);
	checkUOID = tempUOID;								// make it global
	//memcpy(checkUOID,sendHeader.uoid,20);


	pthread_mutex_lock(&NeighborList);																//Apply LOCK
	multimap<string,int> tempMap = node.getNeighborList();
	pthread_mutex_unlock(&NeighborList);																//RELEASE LOCK

	//printf("MY TOTAL NEIGHBORS = %d\n",tempMap.size());
	multimap<string,int>::iterator it;
		
	// flood the message in the network - write the code that you have written for join
	int tempSock;
	for( it=tempMap.begin(); it!=tempMap.end(); it++)
	{
		tempSock = (*it).second;
		//printf("Neighbor socketdesc = %d\n",tempSock);
		pthread_mutex_lock(&WriteQueue[tempSock]);
		writeQueue[tempSock].push_back(msg);			//push to all neighbor the write queue
		pthread_cond_signal(&condition_var_Write[tempSock]);	
		pthread_mutex_unlock(&WriteQueue[tempSock]);

	}


	struct timeval checkFirst, checkLast;
	gettimeofday(&checkFirst, NULL);

	while(1)
	{
		gettimeofday(&checkLast, NULL);

		if(shutdownFlag == true || joinToTheNetworkFlag == true)
		{
			checkFlag = false;
			checkActive = false;
			pthread_exit(NULL);
		}

		if( checkFlag == true)
		{
			pthread_exit(NULL);
		}
		if ((uint32_t)(checkLast.tv_sec - checkFirst.tv_sec) >= node.getMsgLifetime()) 
		{
			joinToTheNetworkFlag = true;
		}
		sleep(1);

	}




	return NULL;
}




